﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace  RzCorportativo
{
    public class Alert
    {
        public Alert(string name, System.Web.UI.Control control)
        {
            this.AlertName = name;
            this.Control = control;
            this.AutoClose = true;
        }

        public System.Web.UI.Control Control { get; set; }

        public Dictionary<string, string> Mensagens = new Dictionary<string, string>();

        public AlertType AlertType { get; set; }

        public bool HasMessage { get { return this.Mensagens.Count > 0; } }

        public string AlertName { get; set; }

        public bool AutoClose { get; set; }

        public void Add(string key, string value)
        {
            if (this.Mensagens.ContainsKey(key))
                throw new Exception("Chave de erro já existente");
            this.Mensagens.Add(key, value);
        }

        public void Remove(string key)
        {
            if (this.Mensagens.ContainsKey(key))
                this.Mensagens.Remove(key);
        }

        public bool Exists(string key)
        {
            return this.Mensagens.ContainsKey(key); 
        }

        public void Show()
        {
            string script = "$alert = new Alert();" +
                            "$alert.Name = '" + this.AlertName + "';" +
                            "$alert.Type = " + ((int)this.AlertType).ToString() + ";";
            if (!this.AutoClose)
                script += "$alert.AutoClose = false;";
            foreach (var item in this.Mensagens)
            {
                script += "$alert.AddMessage('" + item.Value.Replace("'", "").Replace("\r\n", "<br />") + "');";
            }
            script += "$alert.Show();";
            
            System.Web.UI.ScriptManager.RegisterStartupScript(this.Control, this.Control.GetType(), this.AlertName, script, true);
        }

    }
}